package com.example.service.impl;

import com.example.service.ISendEmailService;
import com.example.vo.MailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import javax.mail.internet.MimeMessage;
import java.util.Date;
/**
 * 邮件发送方法实现
 *
 * @author pursueSong
 * 2022-04-22
 */
@Service
public class SendEmailServiceImpl implements ISendEmailService {

    @Autowired
    private JavaMailSenderImpl mailSender;//注入邮箱工具类
    @Autowired
    JavaMailSender javaMailSender;
    /**
     * 创建模板引擎处理器
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发邮件
     * @param mailVo
     * @return
     */
    public MailVo sendMail(MailVo mailVo){
        try{
            checkMail(mailVo);//1.检测邮件
            sendMimeMail(mailVo);//2.发送邮件
        }catch (Exception e){
            //打印错误信息
            System.out.println("发送邮件失败:"+ e);
            mailVo.setStatus("fail");
            mailVo.setError(e.getMessage());
            return mailVo;
        }

        return null;
    }

    /**
     * 检测邮件信息类
     * @param mailVo
     */
    private void checkMail(MailVo mailVo){
        if (StringUtils.isEmpty(mailVo.getTo())){
            throw new RuntimeException("邮件收件人不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getSubject())){
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getText())){
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    /**
     * 构建复杂邮件信息类
     * @param mailVo
     */
    private void sendMimeMail(MailVo mailVo){
        try{
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(),true);
            mailVo.setFrom(getMailSendFrom());//邮件发信人从配置项读取
            messageHelper.setFrom(mailVo.getFrom());//邮件发信人
            messageHelper.setTo(mailVo.getTo().split(","));//邮件收件人
            messageHelper.setSubject(mailVo.getSubject());//邮件主题
            messageHelper.setText(mailVo.getText());//邮件内容
//            FileSystemResource res = new FileSystemResource(new File("C:\\Users\\sinosoft\\Desktop\\akali.JPG"));
//            messageHelper.addInline("p01",res);
            if (!StringUtils.isEmpty(mailVo.getCc())){//抄送
                messageHelper.setCc(mailVo.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailVo.getBcc())){//密送
                messageHelper.setBcc(mailVo.getBcc().split(","));
            }
            if (mailVo.getMultipartFiles() != null){//添加邮件附件
                for (MultipartFile multipartFile : mailVo.getMultipartFiles()){
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(),multipartFile);
                }
            }
            if (StringUtils.isEmpty((CharSequence) mailVo.getSentDate())) {//发送时间
                mailVo.setSentDate(new Date());
                messageHelper.setSentDate(mailVo.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//发送邮件
            mailVo.setStatus("ok");
            System.out.println("发送邮件成功: {}->{}" + "from -->"+mailVo.getFrom()+"TO-->"+mailVo.getTo());

        }catch (Exception e){
            throw new RuntimeException(e);//发送失败
        }

    }

    /**
     * 发送模板邮件
     * @param mailVo
     */
    public MailVo sendTemplateMail(MailVo mailVo,String TemplateSelection) {
        System.err.println(" m -> " +mailVo);
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
//            mailVo.setFrom(getMailSendFrom());//邮件发信人从配置项读取
            messageHelper.setFrom(mailVo.getFrom());//邮件发信人
            messageHelper.setTo(mailVo.getTo().split(","));//邮件收件人
            messageHelper.setSubject(mailVo.getSubject());//邮件主题
            //抄送
            if (!StringUtils.isEmpty(mailVo.getCc())){
                messageHelper.setCc(mailVo.getCc().split(","));
            }
            //密送
            if (!StringUtils.isEmpty(mailVo.getBcc())){
                messageHelper.setBcc(mailVo.getBcc().split(","));
            }
            //添加邮件附件
            if (mailVo.getMultipartFiles() != null){
                for (MultipartFile multipartFile : mailVo.getMultipartFiles()){
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(),multipartFile);
                }
            }
            //发送时间
            if (StringUtils.isEmpty((CharSequence) mailVo.getSentDate())) {
                mailVo.setSentDate(new Date());
                messageHelper.setSentDate(mailVo.getSentDate());
            }
            //使用模板thymeleaf
            Context context = new Context();
            //定义模板数据
            context.setVariables(mailVo.getAttachment());
            //设置类加载模板处理器
            ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
            //设置前缀后缀
            resolver.setTemplateMode("HTML");
            resolver.setCacheable(true);
            resolver.setPrefix("templates/");
            resolver.setSuffix(".html");
            //设置引擎使用的模板文件
            templateEngine.setTemplateResolver(resolver);
            String process = templateEngine.process("InterviewNotice", context);
            if ("聘用".equals(TemplateSelection)){
                process = null;
                process = templateEngine.process("EmploymentNotice", context);
            }
            //获取thymeleaf的html模板
            messageHelper.setText(process,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
            mailVo.setStatus("ok");
            System.out.println("发送邮件成功: {}->{}" + "from -->"+mailVo.getFrom()+"TO-->"+mailVo.getTo());
        } catch (Exception e) {
            System.out.println("模板邮件发送失败->message:{}" + e.getMessage());
            throw new RuntimeException("邮件发送失败");
        }
        return mailVo;
    }


    /**
     * 获取邮件发信人
     * @return
     */
    public String getMailSendFrom(){
        System.err.println("获取邮件发信人" + mailSender.getJavaMailProperties().getProperty("from"));
        return mailSender.getJavaMailProperties().getProperty("from");
    }
}
